package messages

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gopkg.in/gomail.v2"
	"strings"
	"time"
)

// EmailCodeTemplate 邮箱验证码发送模板
const EmailCodeTemplate = `
<strong>尊敬的用户:</strong>
<p style='text-indent:2em;'>
您的验证码为:
	<span style="padding: 0 10px;font-size: 20px;font-weight: bold;color: #2196f3;">[[CODE]]</span>
</p>
<p>出于安全原因，该验证码将于[[EXPIRE]]后失效，请勿将验证码透露给他人</p>
<br><br><br><br>
<span style="color: #c1c1c1;">这一封系统邮件，请勿直接回复。</span>
`
const CodeContentReplace = "[[CODE]]"
const CodeExpireReplace = "[[EXPIRE]]"
const CodeSendInterval = 10 //验证码发送间隔时间，单位：秒

type emailVerifyCodeSender struct {
	codeExpired time.Duration //验证码有效期

	cnf *configstc.EmailConfig

	dialer *gomail.Dialer
	MessageSender
}

func NewEmailVerifyCodeSender(cnf *configstc.EmailConfig) *emailVerifyCodeSender {
	return &emailVerifyCodeSender{
		MessageSender: NewTimeInLimitSender(CodeSendInterval),
		cnf:           cnf,
		codeExpired:   time.Minute * 5,
		dialer:        gomail.NewDialer(cnf.SmtpHost, cnf.SmtpPort, cnf.SmtpUserName, cnf.SmtpPassword),
	}
}

func (s *emailVerifyCodeSender) WithCodeExpired(t time.Duration) *emailVerifyCodeSender {
	s.codeExpired = t
	return s
}

func (s *emailVerifyCodeSender) Send(target string, code string) error {
	cnf := s.cnf

	m := gomail.NewMessage()
	// 这种方式可以添加别名，即 nickname， 也可以直接用<code>m.SetHeader("From", MAIL_USER)</code>
	m.SetHeader("From", cnf.SmtpName+"<"+cnf.SmtpUserName+">")
	// 发送给多个用户
	m.SetHeader("To", target)
	// 设置邮件主题
	m.SetHeader("Subject", "新的验证码~")
	// 设置邮件正文
	m.SetBody("text/html", s.verifyCodeBody(code))

	dialer := gomail.NewDialer(cnf.SmtpHost, cnf.SmtpPort, cnf.SmtpUserName, cnf.SmtpPassword)
	// 发送邮件
	return dialer.DialAndSend(m)
}

// 验证码内容body
func (s *emailVerifyCodeSender) verifyCodeBody(code string) string {
	str := EmailCodeTemplate
	str = strings.ReplaceAll(str, CodeContentReplace, code)
	str = strings.ReplaceAll(str, CodeExpireReplace, fmt.Sprintf("%d分钟", s.codeExpired/time.Minute))
	return str
}
